#!/usr/bin/env python
# coding=UTF-8
import logging
import time
import datetime
from hashlib import md5
import urllib, urllib2
import random, json

import requests
import cherrypy
import redis
from nsq.http import nsqd

import config
import dao
import util

from Crypto.Cipher import AES
import traceback
from binascii import b2a_hex, a2b_hex

from pygeohash import geohash, geohash_haversine_distance
import itertools

def nsq_pub(topic, message):
    try:
        nsq_client = nsqd.Client("http://%s/" % config.NSQ_HTTP)
        if isinstance(message, dict):
            message = json.dumps(message, separators=(',', ':'))
        logging.info(u"推送消息:%s" % message)
        nsq_client.pub(topic, message)
        return True
    except:
        logging.error("nsq send error", exc_info=True)
        return False

pool = redis.ConnectionPool(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB)
_r = redis.Redis(connection_pool=pool)

def get_client_ip():
    header = cherrypy.request.headers
    ip = ''
    ipList = header.get("X-Forwarded-For", "").replace(" ", "").split(",")
    if ipList:
        ip = ipList[0]
        if len(ipList) > 1 and ip[:3] in ('10.', '127', '192', '172'):
            ip = ipList[1]
    if not ip:
        ip = header.get('X-Real-Ip')
    if not ip:
        ip = header.get('Remote-Addr')
    if not ip:
        ip = header.get('REMOTE-ADDR')
    return ip

def create_uid(uid):
    db = dao.Game_DB()
    while 1:
        uid += 1
        if '4' in str(uid):
            continue
        if util.is_good_num(str(uid)):
            db.add_good_num(uid)
            continue
        return uid

def get_phone_model(ua=''):
    #根据ua获取用户手机型号
    if not ua:
        header = cherrypy.request.headers
        ua = header.get("User-Agent", "")
    if "Android" in ua:
        info = ua.split(";")[-1].strip()
        if "MIUI" in info:
            sep = "MIUI"
        else:
            sep = "Build" 
        return info.split(sep)[0].strip()
    elif "iPhone" in ua:
        return "iPhone"
    return ""

def get_wx_user(access_token, openid):
    try:
        url = "http://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN" % (access_token, openid)
        # h = requests.get(url, verify=False)
        # res = h.json()
        logging.info(url)
        h = urllib2.urlopen(url)
        res = h.read()
        logging.info(res)
        res = json.loads(res)
        return res
    except:
        logging.error("wx api error", exc_info=True)
        return {}

def get_ip_data(ip):
    try:
        url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=%s" % ip
        logging.info(url)
        h = urllib2.urlopen(url)
        res = h.read()
        logging.info(res)
        res = json.loads(res)
        return res
    except:
        logging.error("ip error", exc_info=True)
        return {}

def get_gps_data(lat, lon):
    try:
        url = "http://api.map.baidu.com/geocoder/v2/?ak=881ee671d059ace959431fbe7afbde2a&callback=&location=%s,%s&output=json&pois=1" % (lat, lon)
        logging.info(url)
        h = urllib2.urlopen(url)
        res = h.read()
        logging.info(res)
        res = json.loads(res)
        return res['result']['addressComponent']
    except:
        logging.error("ip error", exc_info=True)
        return {}

def convert_gps(lat, lon):
    try:
        url = "http://api.map.baidu.com/geoconv/v1/?coords=%s,%s&from=1&to=5&ak=881ee671d059ace959431fbe7afbde2a" % (lon, lat)
        h = urllib2.urlopen(url)
        res = h.read()
        logging.info(res)
        res = json.loads(res)
        result = res['result'][0]
        return result['y'], result['x']
    except:
        logging.error("ip error", exc_info=True)
        return lat, lon
    
class prpcrypt():
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_CBC
     
    #加密函数，如果text不是16的倍数【加密文本text必须为16的倍数！】，那就补足为16的倍数
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        #这里密钥key 长度必须为16（AES-128）、24（AES-192）、或32（AES-256）Bytes 长度.目前AES-128足够用
        length = 16
        count = len(text)
        add = length - (count % length)
        text = text + ('\0' * add)
        self.ciphertext = cryptor.encrypt(text)
        #因为AES加密时候得到的字符串不一定是ascii字符集的，输出到终端或者保存时候可能存在问题
        #所以这里统一把加密后的字符串转化为16进制字符串
        return b2a_hex(self.ciphertext)
     
    #解密后，去掉补足的空格用strip() 去掉
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip('\0')
    
def send_sms(number, vcode='', msg=''):
    try:
        tradeno = time.strftime("%Y%m%d%H%M%S")
        userPassword = "1Hk6gaAU"
        if not msg:
            msg = u"验证码：%s,如非本人操作请忽略本短信。".encode("utf-8") % str(vcode)
        param = {"userName":"qiduwenhua",
                 "userPassword":"1Hk6gaAU",
                 "phones":number,
                 "content":msg,
                 "etNumber":"",
                 "tradeNo":tradeno,
                 }
        json_param = json.dumps(param, separators=(',',':'))
        pc = prpcrypt("CnKx0LDEpsefVCNN")      #初始化密钥
        sign = pc.encrypt(json_param)
        param['sign'] = sign
        param['userPassword'] = md5(userPassword).hexdigest()
        h = requests.post("http://120.26.125.243:8585/sms/openCard", data=json.dumps(param, separators=(',',':')))
        res = h.text
        #print res
        logging.info("%s->%s" % (number, res))
        res = json.loads(res)
        if res['resCode'] == 'P00000':
            return {"code":0, "msg":"ok"}
        return {"code":501, "msg":res}
    except:
        logging.error("error:%s" % number, exc_info=True)
        return {"code":500, "msg":"error"}

def conf(cp, cv, bid, uid):
    conf_info = {}
    db = dao.Game_DB()
    conf_list = db.get_conf(bid)
    if conf_list:
        for conf in conf_list:
            conf_info[conf['param']] = conf['value']
    wx_login = 'y'
    guest_login = config.guest_login
    if cp == 'ios' and cv == conf_info.get('appstore_cv'):
        guest_login = 'y'
        wx_login = 'n'
    ip = util.get_ip()
    if ip == '183.3.219.244':
        guest_login = 'y'
    update_info = db.check_update(cp, cv)
    if not update_info:
        update_info = {}
    
    card_tips = [{"copy_text":u"111111", "label_text":u"房卡相关:lingdianyule(微信公众号)"},{"copy_text":u"222222", "label_text":u"代理咨询:13488889999(微信)"},{"copy_text":u"333333", "label_text":u"华南咨询:lingdianyule(微信)"},{"copy_text":u"444444", "label_text":u"其他地区咨询:lingdianyule(微信)"},]
    return {"code":0, "msg":"ok", "data":{"card_tips":card_tips,"conf_info":conf_info, "update_info":update_info, "wx_login":wx_login, "guest_login":guest_login, "game_rule":[]}}
    
def login(cp, cv, bid, access_token, openid, devid, login_type):
    db = dao.Game_DB()
    if login_type == 'wx':
        devid = ''
        if not openid:
            return {"code":1000, "msg":"openid not null"}
        user_info = db.get_wx_user(bid, openid)
        if user_info:
            uid = user_info['uid']
            if access_token:
                wx_user_info = get_wx_user(access_token, openid)
                if wx_user_info.get("openid"):
                    head = wx_user_info['headimgurl']
                    name = wx_user_info['nickname'].replace("'"," ")
                    sex = wx_user_info['sex']
                    if head != user_info['head'] or name != user_info['name'] or sex != user_info['sex']:
                        db.update_user(bid, uid, head, name, sex) 
    else:
        user_info = db.get_dev_user(bid, devid)
    tcp_server = db.get_connserver()
    if not tcp_server:
        return {"code":1001, "msg":"系统登录繁忙"}
        #tcp_server = {"ip":"47.93.90.95", "port":8098}
        tcp_server = {}
    ip = get_client_ip()
    if user_info:
        user_info.pop("ctime")
        user_info['pwd'] = user_info['md5pwd']
        user_info.pop("md5pwd")
        
        user_info['ip'] = ip
        user_info['online'] = 'n'
        key = "%s_%s" % (bid, str(user_info['uid']))
        user_data = _r.hgetall(key)
        
        all_joined_rid = []
        rows = db.all_joined_room(bid, user_info['uid'])
        for row in rows:
            all_joined_rid.append(row['rid'])
        
        if user_data and int(user_data.get('rid', 0)) in all_joined_rid:
            joined_room = int(user_data['rid'])
        elif all_joined_rid:
            joined_room = all_joined_rid[0]
        else:
            joined_room = 0
        #get_joined_room = db.get_joined_room(bid, user_info['uid'])
        #if get_joined_room:
        #    joined_room = get_joined_room['rid']
        #else:
        #    joined_room = 0
        
        _r.hmset(key, user_info)
        return {"code":0, "msg":"登录成功",
                "data":{"user_info":user_info,
                        "joined_room":joined_room,
                        "tcp_server":tcp_server,
                        }
                }

    max_uid = db.get_max_uid(bid)
    if not (max_uid and max_uid['uid']):
        uid = 80001
    else:
        uid = create_uid(long(max_uid['uid']))
    if uid < 80001:
        uid = 80001
    if login_type == 'wx':
        wx_user_info = get_wx_user(access_token, openid)
        if not wx_user_info or not wx_user_info.get("openid"):
            return {"code":1001, "msg":"登录失败,获取微信信息异常"}
        head = wx_user_info['headimgurl']
        name = wx_user_info['nickname'].replace("'"," ")
        sex = wx_user_info['sex']
    else:
        #head = ""
        head = "%s/voice/head/%s.png" % (config.UPLOAD_ADDR, uid % 8 + 1)
        phone_model = get_phone_model()
        if phone_model:
            name = phone_model
        else:
            name = u"游客%s" % devid[-4:]
        sex = 1
        openid = ""
    card = 7
    pwd = str(random.randint(100000, 999999))
    pid = 0
    mcard = 60
    i = db.add_user(bid, uid, pwd, openid, head, name, sex, cp, cv, card, pid, devid, mcard)
    if i != 1:
        db.res = False
        return {"code":1002, "msg":"注册账户异常"}
    user_info = {"uid":uid, "pwd":md5(pwd).hexdigest(), "head":head, "name":name, "sex":sex, "ip":ip, "card":card}
    key = "%s_%s" % (bid, str(uid))
    _r.hmset(key, user_info)
    return {"code":0, "msg":"登录成功",
            "data":{"user_info":user_info,
                    "joined_room":0,
                    "tcp_server":tcp_server,
                    }
            }

def get_user_info(bid, uid):
    db = dao.Game_DB()
    data = db.user_info(bid, uid)
    del data['ctime']
    del data['pwd']
    del data['md5pwd']
    user_stat = db.query_user_stat(bid, uid)
    if user_stat:
        for stat in user_stat:
            all_round = stat['all_round']
            win_round = stat['win_round']
            game_type = stat['game_type']
            stat['game_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
            if all_round:
                stat['win_rate'] = "%s%%" % (win_round * 100/ all_round)
            else:
                stat['win_rate'] = "0%"
    else:
        user_stat = [{"game_name":"广东推倒胡", "win_rate":"0%","all_round":0, "win_round":0, "score":0},{"game_name":"转转麻将", "win_rate":"0%","all_round":0, "win_round":0, "score":0},{"game_name":"跑得快", "win_rate":"0%","all_round":0, "win_round":0, "score":0}]
    data['user_stat'] = user_stat
    if not data['pid']:
        data['pid'] = config.DEFAULT_PID
    return {"code":0, "msg":"ok", "data":data}

def set_pid(bid, uid, pid):
    if uid == pid:
        return {"code":2100, "msg":"分享人不能输入自己的ID", "data":{}}
    if not pid:
        return {"code":2100, "msg":"请输入分享人ID", "data":{}}
    db = dao.Game_DB()
    data = db.user_info(bid, uid)
    if data['pid']:
        return {"code":2101, "msg":"该账户已存在分享人,不能修改", "data":{}}
    if not db.user_info(bid, pid):
        return {"code":2102, "msg":"分享人ID不存在", "data":{}}
    db.set_pid(bid, uid, pid)
    return {"code":0, "msg":"操作成功", "data":{}}

def set_signature(bid, uid, signature):
    db = dao.Game_DB()
    db.set_signature(bid, uid, signature)
    return {"code":0, "msg":"操作成功", "data":{}}

def bf_create_club(cp, cv, bid, uid, pwd, lat, lon):
    db = dao.Game_DB()
    user_info = db.user_info(bid, uid)
    if user_info['card'] < 1:
        return {"code":1101, "msg":"您的账户房卡不足"}
    created_club = 0
    rows = db.myclub(bid, uid)
    if rows:
        created_club = len(rows)
        if created_club >= 10:
            return {"code":2201, "msg":"您已创建了10个俱乐部达到了上限"}
    province = ""
    city = ""
    #lat, lon = "", ""
    location = {}
    if lat and lon and lat != '0' and lon != '0':
        location = get_gps_data(lat, lon)
    if not location:
        ip = get_client_ip()
        location = get_ip_data(ip)
    if location:
        province = location.get("province", "").replace(u"省", "")
        city = location.get("city", "").replace(u"市", "")
    tag = []
    return {"code":0, "msg":"ok", "data":{"max_club":10, "created_club":created_club, "province":province, "city":city, "tag":tag}}

def create_club(cp, cv, bid, uid, pwd, name, province, city, head, tag, des):
    if not name:
        return {"code":2301, "msg":"请输入俱乐部名称"}
    db = dao.Game_DB()
    user_info = db.user_info(bid, uid)
    if user_info['card'] < 1:
        return {"code":2302, "msg":"您的账户房卡不足"}
    rows = db.myclub(bid, uid)
    if rows:
        created_club = len(rows)
        if created_club >= 10:
            return {"code":2304, "msg":"您已创建了10个俱乐部达到了上限"}
    
    if not city or city in ("?", u"?"):
        ip = get_client_ip()
        location = get_ip_data(ip)
        if location:
            province = location.get("province", "").replace(u"省", "")
            city = location.get("city", "").replace(u"市", "")
    try:
        (i, cid) = db.add_club(bid, name, uid, head, province, city, des, tag, 500)
        db.join_club(uid, cid, 2, 2)
        return {"code":0, "msg":"ok", "data":{"cid":cid}}
    except:
        db.res = False
        logging.error("create room error:", exc_info=True)
        return {"code":2305, "msg":"创建失败"}

def myclub(bid, uid):
    db = dao.Game_DB()
    mine_club = db.myclub(bid, uid)
    param_conf = db.get_param_conf(bid, 'share_url')
    for club in mine_club:
        cid = club['cid']
        #club_len = db.get_club_member_len(cid)
        #club['join_user'] = club_len['number']
        #club['online_user'] = club_len['online_user']
        club['share_title'] = u"俱乐部%s,ID%s (分享人id:%s)" % (club['name'], cid, uid)
        club['share_des'] = club['des']
        club['share_url'] = "%s/?cid=%s" % (param_conf['value'], cid)
        tag = club['tag']
        if tag:
            tag = tag.split(",")
            club['tag'] = "#"+"    #".join(tag)
    return {"code":0, "msg":"ok", "data":{"mine_club":mine_club}}

def joined_club(bid, uid):
    db = dao.Game_DB()
    mine_club = db.joined_club(bid, uid)
    param_conf = db.get_param_conf(bid, 'share_url')
    for club in mine_club:
        cid = club['cid']
        club['share_title'] = u"俱乐部%s,ID%s (分享人id:%s)" % (club['name'], cid, uid)
        club['share_des'] = club['des']
        club['share_url'] = "%s/?cid=%s" % (param_conf['value'], cid)
        tag = club['tag']
        if tag:
            tag = tag.split(",")
            club['tag'] = "#"+"    #".join(tag)
    return {"code":0, "msg":"ok", "data":{"joined_club":mine_club}}

def find_club(bid, uid, cid='', tag='', city=''):
    db = dao.Game_DB()
    if cid:
        if not cid.isdigit():
            #return {"code":0, "msg":"请输入数字的俱乐部ID", "data":{}}
            clubs = db.query_club_by_city(bid, uid, cid, 20)
            if not clubs:
                clubs = db.query_club_by_name(bid, uid, cid, 20)
        else:
            club = db.get_club(cid)
            if not club:
                clubs = []
            else:
                clubs = [club]
    elif tag:
        clubs = db.query_club_by_tag(tag)
    elif city:
        clubs = db.query_club_by_city(bid, uid, city, 20)
    else:
        clubs = []
    for club in clubs:
        club_len = db.get_club_member_len(club['cid'])
        club['join_user'] = club_len['number']
        tag = club['tag']
        if tag:
            tag = tag.split(",")
            club['tag'] = "#"+"    #".join(tag)
        in_club = db.in_club(club['cid'], uid)
        if in_club:
            club['joined_flag'] = 'y'
            club['verify'] = in_club['verify']
        else:
            club['joined_flag'] = 'n'
            club['verify'] = 0
    if not clubs:
        code = 400
        msg = u"没有找到结果"
    else:
        code = 0
        msg = ""
    return {"code":code, "msg":msg, "data":{"clubs":clubs}}

def recommend_club(bid, uid):
    local_club = []
    db = dao.Game_DB()
    ip = get_client_ip()
    location = get_ip_data(ip)
    city = location.get("city")
    if city:
        local_club = db.query_club_by_city(bid, uid, city, 20)
        for club in local_club:
            #club_len = db.get_club_member_len(club['cid'])
            #club['join_user'] = club_len['number']
            in_club = db.in_club(club['cid'], uid)
            if in_club:
                club['joined_flag'] = 'y'
                club['verify'] = in_club['verify']
            else:
                club['joined_flag'] = 'n'
                club['verify'] = 0
            tag = club['tag']
            if tag:
                tag = tag.split(",")
                club['tag'] = "#"+"    #".join(tag)
    hot_club = db.query_hot_club(bid, uid)
    for club in hot_club:
        in_club = db.in_club(club['cid'], uid)
        if in_club:
            club['joined_flag'] = 'y'
            club['verify'] = in_club['verify']
        else:
            club['joined_flag'] = 'n'
            club['verify'] = 0
        tag = club['tag']
        if tag:
            tag = tag.split(",")
            club['tag'] = "#"+"    #".join(tag)
        #club_len = db.get_club_member_len(club['cid'])
        #club['join_user'] = club_len['number']
    return {"code":0, "msg":"", "data":{"hot_club":hot_club, "local_club":local_club, "city":city}}

def join_club(bid, uid, cid):
    db = dao.Game_DB()
    club_info = db.get_club(cid)
    if not club_info:
        return {"code":2401, "msg":"俱乐部不存在", "data":{}}
    elif club_info['flag'] != 'y':
        return {"code":2402, "msg":"俱乐部已解散", "data":{}}
    if db.in_club(cid, uid):
        return {"code":0, "msg":"", "data":{"club_info":club_info}}
    i = db.join_club(uid, cid, 0, 0)
    if i == 0:
        return {"code":2403, "msg":"已经在俱乐部当中", "data":{}}
    
    return {"code":0, "msg":"加入申请已提交,请等待审核", "data":{"club_info":club_info}} 

def unverify_member(bid, cid, uid):
    db = dao.Game_DB()
    myrole = db.get_myrole(cid, uid)
    if not myrole or myrole['role'] < 1:
        apply_user = []
    else:
        apply_user = db.unverify_member(bid, cid)
        
    return {"code":0, "msg":"ok", "data":{"apply_user":apply_user}}

def join_verify(cid, bid, uid, member, verify):
    db = dao.Game_DB()
    myrole = db.get_myrole(cid, uid)
    if not myrole or myrole['role'] < 1:
        return {"code":2501, "msg":"你不是管理员不能审核用户", "data":{}}
    if str(verify) == '0':
        db.quit_club(cid, member)
        #db.update_join_user(bid, cid, -1)
    else:
        db.verify_club_member(cid, member, verify)
        db.update_join_user(bid, cid, 1)
    return {"code":0, "msg":"操作成功", "data":{}}

def club_member(cid, bid, uid, member, act):
    #act:list/del/set_manager/unset_manager
    db = dao.Game_DB()
    myrole = db.get_myrole(cid, uid)
    if not myrole:
        return {"code":2511, "msg":"你不是俱乐部成员", "data":{}}
    role = myrole['role']
    if act == 'set_manager':
        if role != 2:
            return {"code":2512, "msg":"你不是创建者不能进行操作", "data":{}}
        db.set_club_member(cid, member, 1, 2)
    elif act == 'unset_manager':
        if role != 2:
            return {"code":2513, "msg":"你不是创建者不能进行操作", "data":{}}
        db.set_club_member(cid, member, 0, 2)
    elif act == 'del':
        get_joined_game = db.get_joined_game(member, cid)
        if get_joined_game:
            return {"code":2531, "msg":"玩家报名了牌局,不能删除"}
        if role < 1:
            return {"code":2514, "msg":"你不是管理员,不能剔除用户", "data":{}}
        db.quit_club(cid, member)
        db.update_join_user(bid, cid, -1)
    rows = db.club_member(bid, cid)
    return {"code":0, "msg":"操作成功", "data":{"club_member":rows}}

def club_set(cid, name, head, des, bg_pic, tag):
    db = dao.Game_DB()
    club = db.get_club(cid)
    if not club:
        return {"code":2521, "msg":"俱乐部不存在", "data":{}}
    if name:
        db.update_club_col(cid, "name", name)
    if head:
        db.update_club_col(cid, "head", head)
    if des:
        db.update_club_col(cid, "des", des)
    if bg_pic:
        db.update_club_col(cid, "bg_pic", bg_pic)
    if tag:
        tag = tag.replace(" ",",")
        db.update_club_col(cid, "tag", tag)
    db.commit()
    club = db.get_club(cid)
    return {"code":0, "msg":"操作成功", "data":{"club":club}}

def club_info(bid, cid, uid):
    started_game = []
    nostart_game = []
    db = dao.Game_DB()
    club = db.get_club(cid)
    if not club:
        club = {}
    else:
        myrole = db.get_myrole(cid, uid)
        if myrole:
            club['verify'] = myrole['verify']
            club['role'] = myrole['role']
        else:
            club['verify'] = 0
            club['role'] = 0
        club_len = db.get_club_member_len(cid)
        club['join_user'] = club_len['number']
        club['online_user'] = club_len['online_user']
        
        param_conf = db.get_param_conf(bid, 'share_url')
        club['share_title'] = u"俱乐部:%s,ID%s (分享人id:%s) " % (club['name'], cid, uid)
        club['share_des'] = club['des']
        club['share_url'] = "%s/?cid=%s" % (param_conf['value'], cid)
        tag = club['tag']
        if tag:
            tag = tag.split(",")
            club['tag'] = " ".join(tag)
        all_joined_gid = []
        all_joined_game = db.all_joined_game(uid, cid)
        if all_joined_game:
            for joined_game in all_joined_game:
                all_joined_gid.append(joined_game['gid'])
            
        #获取当前俱乐部的招募中和进行中的牌局
        #started_game = db.club_games(cid, 1)
        started_game = []
        for game in started_game:
            gid = game['gid']
            game_member = db.get_game_count(gid)
            game['join_player'] = game_member['c']
            game['share_title'] = u"俱乐部ID:%s 牌局:%s (分享人id:%s)" % (cid, game['name'], uid)
            game['share_des'] = game['game_des']
            game['share_url'] = "%s/?gid=%s" % (param_conf['value'], gid)
            game_type = game['game_type']
            game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        #nostart_game = db.club_games(cid, 0)
        nostart_game = []
        for game in nostart_game:
            gid = game['gid']
            game_member = db.get_game_count(gid)
            game['join_player'] = game_member['c']
            game['share_title'] = u"俱乐部ID:%s 牌局:%s(分享人id:%s) 人数:%s/%s" % (cid, game['name'], uid, game_member['c'], game['all_player'])
            game['share_des'] = game['game_des']
            game['share_url'] = "%s/?gid=%s" % (param_conf['value'], gid)
            if gid in all_joined_gid:
                game['joined_flag'] = 'y'
            else:
                game['joined_flag'] = 'n'
            game_type = game['game_type']
            game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        
    return {"code":0, "msg":"ok", "data":{"club":club, "nostart_game":nostart_game, "started_game":started_game, "joined_game":""}}

def create_game(cid, name, game_type, player, all_round, all_player, rule):
    logging.info(u"==========",all_round,"==========",rule)
    if not name:
        return {"code":2600, "msg":"请输入牌局名称", "data":{}}
    all_player = int(all_player)
    player = int(player)
    if all_player % player != 0 or all_player < player:
        return {"code":2601, "msg":"all_player error", "data":{}}
    if game_type == 'ldfpf':
        all_round = 1000
    elif game_type == 'ddz':
        all_round = int(all_round)
        if all_round not in (6, 12, 20):
            return {"code":1100, "msg":"牌局局数设置错误"}
    elif game_type == 'ygmj':
        all_round = int(all_round)
        if all_round not in (6, 12):
            return {"code":1100, "msg":"牌局局数设置错误"}
    else:
        all_round = int(all_round)
        if all_round not in (8, 16, 10, 20):
            return {"code":2602, "msg":"all_round error", "data":{}}
    
    db = dao.Game_DB()
    #nostart_game = db.club_games(cid, 0)
    #if len(nostart_game) >= 30:
    #    return {"code":1100, "msg":"招募中的牌局不能超过30个"}
    rules = {}
    if rule:
        for r in rule.split(","):
            k, v = r.split("=")
            rules[k] = v
    game_des = u"俱乐部ID:%s %s" % (cid, config.GAME_TYPE_NAME.get(game_type, ""))
    game_des += u" %s局" % all_round
    horse = int(rules.get("horse", 0))
    card_num = "16"
    if game_type == 'pdk':
        must_put = rules.get("must_put", "y")
        release_duty = rules.get("release_duty", "y")
        closed_double = rules.get("closed_double", "y")
        card_num = rules.get("card_num", '16')
        show_left_card = rules.get("show_left_card", 'y')
        black_three_first = rules.get("black_three_first", "n")
        rules['card_num'] = card_num
        if must_put == 'y':
            game_des += u"有牌必出  全关加倍"
        else:
            game_des += u"可不出  全关加倍" 
        if show_left_card == "y":
            game_des += u" 显示牌数"
        else:
            game_des += u" 不显牌数"
        if black_three_first == 'y':
            game_des += u" 首局出黑桃3"
            
    elif game_type == 'ldfpf':
        end_huxi = rules.get("end_huxi", 200)
        rules['end_huxi'] = end_huxi
        game_des = u"娄底放炮罚 , 15胡起胡, %s胡封顶 " % end_huxi
    elif game_type == 'ddz':
        max_bomb = rules.get("max_bomb", 5)
        rules['max_bomb'] = max_bomb
        rules['card_warning'] = 2
        game_des = u"斗地主 , %s炸封顶 " % max_bomb
    elif game_type == 'ygmj':
        jiazi = rules.get("jiazi",'n')
        rules["jiazi"] = jiazi
        game_des = u"余干麻将"
    else:
        if horse:
            game_des += u"%s马" % horse
        grab_bar_win = rules.get("grab_bar_win")
        if grab_bar_win == 'y':
            game_des += u",可抢杠胡"
        bar_win_duty = rules.get("bar_win_duty")
        if bar_win_duty == 'y':
            game_des += u",杠爆全包"
        seven_pair_win = rules.get("seven_pair_win")
        if seven_pair_win == 'y':
            game_des += u",可七对胡"
    i, gid = db.add_game(cid, name, game_type, player, all_round, all_player, game_des)
    for k, v in rules.iteritems():
        db.add_game_rule(gid, k, v)
        
    return {"code":0, "msg":"ok", "data":{"gid":gid}}

def quit_game(gid, bid, uid):
    db = dao.Game_DB()
    game = db.get_game(gid)
    if not game:
        return {"code":2611, "msg":"牌局不存在"}
    status = game['status']
    if status == 2:
        return {"code":2612, "msg":"牌局已结束"}
    elif status == 1:
        return {"code":2612, "msg":"牌局已开始,不能取消"}
    db.del_game_member(gid, uid)
    cid = game['cid']
    club = db.get_club(cid)
    all_joined_gid = []
    all_joined_game = db.all_joined_game(uid, cid)
    if all_joined_game:
        for joined_game in all_joined_game:
            all_joined_gid.append(joined_game['gid'])
    nostart_game = db.club_games(cid, 0)
    param_conf = db.get_param_conf(bid, 'share_url')
    if nostart_game:
        nostart_game = nostart_game[:30]
    for game in nostart_game:
        game_member = db.get_game_count(game['gid'])
        game['join_player'] = game_member['c']
        game['share_title'] = u"俱乐部ID:%s 牌局:%s(分享人id:%s) 人数:%s/%s" % (cid, game['name'], uid, game_member['c'], game['all_player'])
        game['share_des'] = game['game_des']
        game['share_url'] = "%s/?gid=%s" % (param_conf['value'], game['gid'])
        if game['gid'] in all_joined_gid:
            game['joined_flag'] = 'y'
        else:
            game['joined_flag'] = 'n'
        game_type = game['game_type']
        game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
    db.update_club_online(cid, uid, 'y')
    return {"code":0, "msg":"取消报名", "data":{"nostart_game":nostart_game}}

def enroll_game(gid, bid, uid):
    db = dao.Game_DB()
    game = db.get_game(gid)
    if not game:
        return {"code":2611, "msg":"牌局不存在"}
    status = game['status']
    if status == 2:
        return {"code":2612, "msg":"牌局已结束"}
    cid = game['cid']
    joined_nostart_game = db.joined_nostart_game(uid, cid)
    if joined_nostart_game:
        return {"code":26122, "msg":"您已报名其他牌局，请完成后再报名"}
    joined_started_game = db.joined_started_game(uid, cid)
    if joined_started_game:
        joined_gid = joined_started_game['gid']
        ing_room = db.get_rid_by_gid(uid, joined_gid)
        if ing_room:
            room_info = db.get_room(ing_room['rid'], bid)
            if room_info['flag'] == 'y':
                return {"code":26122, "msg":"请先完成之前的牌局再来报名"}
    player = int(game['player'])
    all_player = int(game['all_player'])
    now_player = db.get_game_count(gid)['c']
    logging.info("%s,%s" % (now_player, all_player))
    if now_player >= all_player:
        return {"code":2613, "msg":"牌局人数已满,不能再报名"}
    
    #myrole = db.get_myrole(cid, uid)
    #if myrole:
    #    verify = myrole['verify']
    #    role = myrole['role']
    #    if role !=0:
    #        return {"code":2616, "msg":"管理员不能报名"}
    #    if verify != 2:
    #        return {"code":2617, "msg":"你还没有报名参与牌局的资格"}    
    
    club = db.get_club(cid)
    bid = club['bid']
    admin = club['admin']
    game_type = game['game_type']
    all_round = int(game['all_round'])
    if all_round in (8, 10):
        card = 1
    elif all_round in (16, 20):
        card = 2
    elif all_round == 1000:
        card = 1
    else:
        if game_type == 'ddz':
            if all_round == 6:
                card = 2
            elif all_round == 12:
                card = 3
            elif all_round == 20:
                card = 5
            else:
                return {"code":1301, "msg":"牌局创建局数错误"}
        else:
            return {"code":1301, "msg":"牌局创建局数错误"}
    ip = get_client_ip()
    if not db.get_game_member(gid, uid):
        db.add_game_member(gid, uid, ip)
        db.commit()
    rules = {}
    game_rule = db.game_rule(gid)
    for r in game_rule:
        k = r['param']
        v = r['value']
        rules[k] = v
    now_player = db.get_game_count(gid)['c']
    joined_room = 0
    if now_player == all_player:
        db.update_game_status(gid, 1)
        #开始创建房间,分配房间
        game_members = db.game_members(gid)
        game_members = list(game_members)
        random.shuffle(game_members)
        room_num = all_player / player
        #rid_list = create_rid(bid, room_num)
        for i in range(room_num):
            #rid = rid_list[i]
            #n = db.add_room(rid, bid, game_type, admin, all_round, card, player, gid, 0, 1, 1, game['game_des'], cid)
            (n, rid) = db.add_room(None, bid, game_type, admin, all_round, card, player, gid, 0, 1, 1, game['game_des'], cid)
            for j in range(player):
                idx = i * player + j
                member = game_members[idx]
                ip = member['ip']
                p_uid = member['uid']
                if str(p_uid) == uid:
                    joined_room = rid
                if j == 0:
                    room_info = {"gid":gid,"cid":cid, "status":"", "admin":admin, "dealer":p_uid, "bid":bid, "last_get_user":p_uid, "game_round":1, "all_round":all_round, "card":card, "game_type":game_type, "horse":rules.get('horse', 'n'), "grab_bar_win":rules.get('grab_bar_win', 'n'), "grab_bar_duty":rules.get('grab_bar_duty', 'n'), "bar_win_duty":rules.get('bar_win_duty', 'n'), "seven_pair_win":rules.get('seven_pair_win', 'n'), "card_num":rules.get('card_num', 16), "end_huxi":rules.get('end_huxi', 200)}
                    _r.hmset("r:%s" % rid, room_info)
                logging.info(u"牌局%s玩家%s分配房间%s" % (gid, p_uid, rid))
                db.add_player(0, gid, rid, p_uid, 0, 'n', ip, '', '', j+1)
                _r.rpush("r:%s:p" % rid, p_uid)
                _r.hset("%s_%s" %(bid, p_uid), "rid", rid)
    
    all_joined_gid = []
    all_joined_game = db.all_joined_game(uid, cid)
    if all_joined_game:
        for joined_game in all_joined_game:
            all_joined_gid.append(joined_game['gid'])
            
    nostart_game = db.club_games(cid, 0)
    param_conf = db.get_param_conf(bid, 'share_url')
    for game in nostart_game:
        gid = game['gid']
        game_member = db.get_game_count(gid)
        game['join_player'] = game_member['c']
        game['share_title'] = u"俱乐部ID:%s 牌局:%s(分享人id:%s) 人数:%s/%s" % (cid, game['name'], uid, game_member['c'], game['all_player'])
        game['share_des'] = game['game_des']
        game['share_url'] = "%s/?gid=%s" % (param_conf['value'], gid)
        if gid in all_joined_gid:
            game['joined_flag'] = 'y'
        else:
            game['joined_flag'] = 'n'
        game_type = game['game_type']
        game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        
    db.update_club_online(cid, uid, 'y')
    return {"code":0, "msg":"操作成功", "data":{"rid":joined_room, "nostart_game":nostart_game}}

def game_member(bid, gid):
    db = dao.Game_DB()
    game_info = db.get_game(gid)
    if game_info:
        if game_info['status'] == 0:
            rows = db.ungame_member(bid, gid)
        else:
            rows = db.game_member(bid, gid)
            #for row in rows:
            #    row['rid'] = str(row['rid'])
    else:
        rows = []
    return {"code":0, "msg":"操作成功", "data":{"game_member":rows}}

def joined_rid(bid, uid):
    rid = 0
    code = 2521
    msg = ""
    if uid:
        db = dao.Game_DB()
        joined_room = db.get_joined_rid(bid, uid)
        if joined_room:
            rid = joined_room['rid']
            code = 0
            if joined_room['mid']:
                msg = u"比赛开始,请准备进入房间"
            elif joined_room['gid']:
                msg = u"俱乐部牌局开始,请准备进入房间"
            else:
                msg = u"游戏开始,请准备进入房间"
            
    return {"code":code, "msg":msg, "data":{"rid":rid}}

def started_game(cid, bid, uid, pwd):
    db = dao.Game_DB()
    club = db.get_club(cid)
    started_game = db.club_games(cid, 1)
    param_conf = db.get_param_conf(bid, 'share_url')
    for game in started_game:
        gid = game['gid']
        game_member = db.get_game_count(gid)
        game['join_player'] = game_member['c']
        game['share_title'] = u"俱乐部:%s,ID%s 牌局:%s(分享人id:%s)" % (club['name'], cid, game['name'], uid)
        game['share_des'] = game['game_des']
        game['share_url'] = "%s/?gid=%s" % (param_conf['value'], gid)
        game_type = game['game_type']
        game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
    return {"code":0, "msg":"", "data":{"started_game":started_game}}

def nostart_game(cid, bid, uid, pwd):
    db = dao.Game_DB()
    club = db.get_club(cid)
    nostart_game = db.club_games(cid, 0)
    all_joined_gid = []
    all_joined_game = db.all_joined_game(uid, cid)
    if all_joined_game:
        for joined_game in all_joined_game:
            all_joined_gid.append(joined_game['gid'])
    param_conf = db.get_param_conf(bid, 'share_url')
    if nostart_game:
        nostart_game = nostart_game[:30]
    for game in nostart_game:
        gid = game['gid']
        game_member = db.get_game_count(gid)
        game['join_player'] = game_member['c']
        game['share_title'] = u"俱乐部ID:%s 牌局:%s(分享人id:%s) 人数:%s/%s" % (cid, game['name'], uid, game_member['c'], game['all_player'])
        game['share_des'] = game['game_des']
        game['share_url'] = "%s/?gid=%s" % (param_conf['value'], gid)
        if gid in all_joined_gid:
            game['joined_flag'] = 'y'
        else:
            game['joined_flag'] = 'n'
        game_type = game['game_type']
        game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
    return {"code":0, "msg":"", "data":{"nostart_game":nostart_game}}

def ended_game(cid, bid, uid, pwd):
    db = dao.Game_DB()
    rows = db.ended_games(cid)
    if rows:
        rows = rows[:30]
    for game in rows:
        gid = game['gid']
        game_member = db.get_game_count(gid)
        game['join_player'] = game_member['c']
        game_type = game['game_type']
        game['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
    return {"code":0, "msg":"", "data":{"ended_game":rows}}

def room_list(gid):
    db = dao.Game_DB()
    rows = db.game_stat(gid)
    return {"code":0, "msg":"", "data":{"room_list":rows, "room_stat":room_stat}}

def room_stat(gid, rid=''):
    db = dao.Game_DB()
    #rows = db.room_stat(gid, rid)
    rows = db.game_stat(gid)
    return {"code":0, "msg":"", "data":{"room_stat":rows}}

def quit_club(cid, bid, uid, pwd):
    db = dao.Game_DB()
    get_joined_game = db.get_joined_game(uid, cid)
    if get_joined_game:
        return {"code":2531, "msg":"您报名了牌局,不可退出俱乐部"}
    db.quit_club(cid, uid)
    db.update_join_user(bid, cid, -1)
    rows = db.all_joined_game(uid, cid)
    for row in rows:
        gid = row['gid']
        db.del_game_member(gid, uid)
    return {"code":0, "msg":"退出成功"}

def dismiss_club(cid, bid, uid, pwd):
    db = dao.Game_DB()
    club = db.get_club(cid)
    if not club or str(club['admin']) != uid:
        return {"code":2541, "msg":"你不是创建者,不能解散"}
    start_game = db.club_games(cid, 1)
    nostart_game = db.club_games(cid, 0)
    if start_game or nostart_game:
        return {"code":2542, "msg":"俱乐部有牌局,不可解散"}
    db.dismiss_club(cid, bid, uid)
    return {"code":0, "msg":"解散成功"}

def create_rid(bid, num=1):
    res = []
    db = dao.Game_DB()
    while len(res) < num:
        rid = random.randint(102001, 999999)
        if rid in res:
            continue
        else:
            if db.get_room(rid, bid):
                continue
            else:
                res.append(rid)
    return res

def create_room(cp, cv, bid, uid, pwd, player, game_type, all_round, gps_lat, gps_lon, rule, create_type=None):
    #create_type:代开房间
    ip = get_client_ip()
    if all_round:
        all_round = int(all_round)
    if game_type == 'ldfpf':
        card = 1
        all_round = 1000
    elif game_type == 'ddz':
        all_round = int(all_round)
        if all_round == 6:
            card = 2
        elif all_round == 12:
            card = 3
        elif all_round == 20:
            card = 5
        else:
            return {"code":1100, "msg":"all_round error"}
    elif game_type in ('gz', 'pcd'):
        if all_round == 4:
            card = 1
        elif all_round == 8:
            card = 2
        else:
            return {"code":1100, "msg":"all_round error"}
    elif game_type=='ygmj':
        if all_round==6:
            card =1
        elif all_round==12:
            card =2
    elif game_type == 'gdy':
        if all_round == 3:
            card = 1
        elif all_round == 6:
            card = 2
        else:
            return {"code":1100, "msg":"all_round error"}
    else:
        all_round = int(all_round)
        if all_round in (8, 10):
            card = 1
        elif all_round in (16, 20):
            card = 2
        else:
            return {"code":1100, "msg":"all_round error"}
    
    rules = {}
    if rule:
        for r in rule.split(","):
            k, v = r.split("=")
            rules[k] = v
    horse = int(rules.get("horse", 0))
    grab_bar_win = rules.get("grab_bar_win", "n")
    grab_bar_duty = rules.get("grab_bar_duty", "n")
    bar_win_duty = rules.get("bar_win_duty", "n")
    seven_pair_win = rules.get("seven_pair_win", "n")
    dealer_mode = rules.get("dealer_mode", "")
    game_mode = rules.get("game_mode", "")
    jiazi = rules.get("jiazi","n")
    player = int(player)
    max_bomb = 0
    if game_type in ('pdk', "ldfpf", "ddz"):
        player = 3
    elif game_type in ('dn', 'ttz', 'sg', 'gdy'):
        pass
    else:
        player = 4
    rules['player'] = player
    db = dao.Game_DB()
    user_info = db.user_info(bid, uid)
    if not create_type or create_type == '0':
        get_joined_room = db.get_joined_room(bid, uid)
        if get_joined_room:
            return {"code":1100, "msg":"请先退出之前加入的房间"}
    #row = db.enrolled_match(bid, uid)
    #if row:
    #    return {"code":2716, "msg":"请先完成其他未完成的比赛", "data":{}}
    #row = db.enrolled_game(bid, uid)
    #if row:
    #    return {"code":2717, "msg":"您已报名俱乐部牌局,请结束后再创建房间", "data":{}}
    
    if user_info['card'] < card:
        return {"code":1101, "msg":"您的账户房卡不足"}
    try:
        must_put = 'y'
        black_three_first = 'n'
        card_warning = '1'
        share_des = u""
        end_huxi = 200
        card_num = "16"
        base = 1
        add_joker = int(rules.get("add_joker", 0))
        if game_type == 'pdk':
            card_num = rules.get("card_num")
            if not card_num:
                card_num = "16"
                rules['card_num'] = card_num
            
            must_put = rules.get("must_put", "y")
            #release_duty = rules.get("release_duty", "y")
            #closed_double = rules.get("closed_double", "y")
            black_three_first = rules.get("black_three_first", "n")
            show_left_card = rules.get("show_left_card", "y")
            card_warning = rules.get("card_warning", "1")
            if not card_warning.isdigit():
                return {"code":1101, "msg":"请选择正确的报牌张数"}
            if must_put == 'y':
                share_des = u"跑得快 有牌必出 放走包赔 全关加倍"
            else:
                share_des = u"跑得快 可不出 放走包赔 全关加倍" 
            if black_three_first == "y":
                share_des += u" 首局出黑桃3"
            if show_left_card == "y":
                share_des += u" 显示牌数"
            else:
                share_des += u" 不显示牌数"
            share_des += u" 【%s】局 %s张玩法 , 速度加入" % (all_round, card_num)
            #share_des += u" %s张报牌" % card_warning
        elif game_type == 'ldfpf':
            end_huxi = rules.get("end_huxi", 200)
            share_des = u"娄底放炮罚 , 15胡起胡, %s胡封顶 " % end_huxi
        elif game_type == 'ddz':
            max_bomb = rules.get("max_bomb", 5)
            card_warning = 2
            share_des = u"斗地主 , %s炸封顶 " % max_bomb
        elif game_type == 'gz':
            card_pack = rules.get("card_pack", 6)
            share_des = u" %s副牌 " % card_pack
            if add_joker:
                share_des += u" 额外加%s王" % add_joker
        elif game_type == 'pcd':
            card_pack = rules.get("card_pack", 6)
            share_des = u" %s副牌 " % card_pack
            if add_joker:
                share_des += u" 额外加%s个机动王" % add_joker
        elif game_type == 'sg':
            base = rules.get("base")
            if not base:
                rules['base'] = 1
            share_des = u"三公 , %s人%s局 " % (player, all_round)
            if dealer_mode == 'fix':
                share_des += u" 固定庄"
            elif dealer_mode == 'p_9':
                share_des += u" 9点上庄"
            elif dealer_mode == 'melee':
                share_des += u" 大混战"
        elif game_type == 'dn':
            share_des = u"经典斗牛 ,"
            if dealer_mode == 'fix':
                share_des += u" 固定庄"
            elif dealer_mode == 'turn':
                share_des += u" 轮庄"
            elif dealer_mode == 'rob':
                share_des += u" 抢庄"
        elif game_type == 'gdy':
            if not game_mode:
                game_mode = 'classic'
                rules['game_mode'] = game_mode
            if game_mode == 'classic':
                share_des = u"经典模式 ,%s局 " % (all_round)
            else:
                share_des = u"火拼模式 ,%s局 " % (all_round)
        elif 'mj' in game_type:
            horse = rules.get("horse", 0)
            if horse:
                share_des += u"%s马,%s局" % (horse, all_round)
            else:
                share_des += u"无马,%s局" % all_round
            if rules.get("seven_pair_win") == 'y':
                share_des += u",可胡七对"
            if rules.get("grab_bar_win") == 'y':
                share_des += u",可抢杠胡"
            if rules.get("bar_win_duty") == 'y':
                share_des += u",杠爆全包"
        elif game_type=='ygmj':
            if jiazi=='n':
                share_des+=u"余干麻将"
            else:
                share_des+=u"余干麻将，夹子玩法"
        else:
            share_des += u" 【%s】局 , 速度加入" % all_round
        # 创建房间
        rid_list = create_rid(bid, 1)
        rid = rid_list[0]
        if not create_type or create_type == '0':
            create_type = 0
        else:
            create_type = 1
            has_created_room = db.created_room(uid, 'y')
            if len(has_created_room) >= 10:
                return {"code":11001, "msg":"只能代开10个未开始的房间"}
        i = db.add_room(rid, bid, game_type, uid, all_round, card, player, 0, 0, 1, 1, share_des, 0, create_type)
        if i != 1:
            return {"code":1101, "msg":"系统繁忙,请重试"}
        for k, v in rules.iteritems():
            db.add_room_rule(rid, k, v)
        game_type_name = config.GAME_TYPE_NAME.get(game_type, game_type)
        share_title = game_type_name
        share_title += u" 房间号【%s】 (分享人id:%s)" % (rid, uid)
        
        # 添加房主玩家
        seat = 1
        base_score = 1000
        if game_type in ('ldfpf', 'dn', 'sg', 'gz'):
            base_score = 0
        if not create_type:
            db.add_player(0, 0, rid, uid, 0, 'y', ip, gps_lat, gps_lon, seat, base_score)
            _r.rpush("r:%s:p" % rid, uid)
            for seat in range(2, player + 1):
                db.add_player(0, 0, rid, 0, 0, 'n', '', '', '', seat, base_score)
                _r.rpush("r:%s:p" % rid, '')
        else:
            for seat in range(1, player + 1):
                db.add_player(0, 0, rid, 0, 0, 'n', '', '', '', seat, base_score)
                _r.rpush("r:%s:p" % rid, '')
        if not nsq_pub("status", {"b":bid, "u":str(uid), "d":{"act":"create_room", "base":base,"create_type":create_type,"uid":uid, "rid":rid, "bid":bid, "player":player, 
                                                              "card":card, "all_round":all_round, "game_type":game_type, "horse":horse, "grab_bar_win":grab_bar_win, 
                                                              "grab_bar_duty":grab_bar_duty, "bar_win_duty":bar_win_duty, "seven_pair_win":seven_pair_win, "must_put":must_put, 
                                                              "black_three_first":black_three_first, "card_warning":card_warning, "end_huxi":end_huxi, "max_bomb":max_bomb, 
                                                              "card_num":card_num, "dealer_mode":dealer_mode, "game_mode":game_mode,"jiazi":jiazi}}):
            db.res = False
            return {"code":1102, "msg":"处理超时"}
        param_conf = db.get_param_conf(bid, 'share_url')
        share_url = "%s/?rid=%s" % (param_conf['value'], rid)
        auto_put = "n"
        if not create_type or create_type == '0':
            return join_room(cp, cv, bid, uid, pwd, rid, gps_lat, gps_lon)
        #return {"code":0, "msg":"ok", "data":{"rid":rid, "create_type":create_type}}
        return created_room(cp, cv, bid, uid, pwd)
        #return {"code":0, "msg":"ok", "data":{"all_round":all_round,"seat":1, "auto_put":auto_put, "rules":rules, "game_type_name":game_type_name, "game_type":game_type, "sex":user_info['sex'], "ip":ip, "base_score":base_score, "rid":rid, "share_url":share_url, "share_title":share_title, "share_des":share_des}}
    except:
        db.res = False
        logging.error("create room error:", exc_info=True)
        return {"code":1103, "msg":"创建失败"}

def cal_distance(lat1, lon1, lat2, lon2):
    if not (lat1 and lon1 and lat2 and lon2):
        return u"未知"
    elif lat1 == '0' or lon1 =='0' or lat2 == '0' or lon2 == '0':
        return u"未知"
    a = geohash.encode(float(lat1), float(lon1))
    b = geohash.encode(float(lat2), float(lon2))
    distance = int(geohash_haversine_distance(a, b))
    if distance > 1000:
        distance = u"%.2f公里" % (distance/1000.0)
    else:
        distance = u"%s米" % distance
    #logging.info(distance)
    return distance
    
def join_room(cp, cv, bid, uid, pwd, rid, gps_lat, gps_lon):
    ip = get_client_ip()
    db = dao.Game_DB()
    user_info = db.user_info(bid, uid)
    if not user_info:
        return {"code":1200, "msg":"uid不存在"} 
    room_info = db.get_room(rid, bid)
    if not room_info:
        return {"code":1200, "msg":"该房间不存在"}
    if room_info['flag'] != 'y':
        return {"code":1201, "msg":"该房间已结束"}
    room = _r.hgetall("r:%s" % rid)
    dealer = room.get('dealer', 0)
    if dealer:
        room_info['dealer'] = int(dealer)
        room_info['game_round'] = int(room.get('game_round', 1))
    else:
        room_info['dealer'] = room_info['admin']
    room_info.pop("ctime")
    room_status = room.get('status', '')
    if not room_status:
        room_status = ''
    room_info['room_status'] = room_status
    if cp == 'ios' and gps_lat and gps_lon:
        gps_lat, gps_lon = convert_gps(gps_lat, gps_lon)
        
    #row = db.enrolled_match(bid, uid)
    #if row:
    #    return {"code":2716, "msg":"请先完成其他未完成的比赛", "data":{}}
    #row = db.enrolled_game(bid, uid)
    #if row:
    #    return {"code":2717, "msg":"您已报名俱乐部牌局,请结束后再创建房间", "data":{}}
    get_joind_room = db.get_joined_room(bid, uid)
    if get_joind_room:
        if get_joind_room['rid'] == int(rid):
            seat = get_joind_room['seat']
            status = get_joind_room['status']
            i = db.return_room(rid, seat, uid, status, 'y', ip, gps_lat, gps_lon)
            i = 1
        else:
            return {"code":1100, "msg":"请先退出之前加入的房间"}

    else:
        # 新加入房间
        row = db.get_free_seat(rid)
        if not row:
            return {"code":1202, "msg":"该房间人员已满"}
        seat = row['seat']
        i = db.join_room(rid, seat, uid, 0, 'y', ip, gps_lat, gps_lon)
    if i != 1:
        db.res = False
        return {"code":1203, "msg":"进入房间失败"}
    match_id = room_info['mid']
    gid = room_info['gid']
    ranking = "0"
    if match_id:
        match_member_info = db.match_member_info(match_id, uid)
        score = match_member_info['score']
        auto_put = "y"
        room_type = "match"
        
        match = db.match_info(bid, match_id)
        mround = match['mround'] - 1
    else:
        mround = 0
        score = 1000
        if room_info['game_type'] in ('ldfpf', 'gz', 'sg', 'dn'):
            score = 0
        auto_put = "n"
        if gid:
            room_type = "club"
        else:
            room_type = "card"
    
    # 获取房间所有玩家信息
    gps_members = []
    players = db.query_room_players(rid, bid)
    #for p in players:
    #    p_uid = str(p['uid'])
    #    if p_uid != str(uid):
    #        gps_members.append(p)
    
    location_info = u""
    location_list = []
    for (p1, p2) in itertools.combinations(players, 2):
        distance = cal_distance(p1['gps_lat'], p1['gps_lon'], p2['gps_lat'], p2['gps_lon'])
        text = u"%s与%s距离:%s\n" % (p1['name'], p2['name'], distance)
        logging.info(text)
        if str(p1['uid'])!= uid and str(p2['uid']) != uid: 
            location_info += text
        location_list.append(text)
    for p in players:
        pranking = "0"
        p['ranking'] = pranking
        p['location_info'] = location_info
    
    if not nsq_pub("status", {"b":bid, "u":str(uid), "d":{"location_info":location_info, "location_list":location_list, "ranking":ranking, "sex":user_info['sex'],"act":"join_room", "uid":uid, "rid":rid, "bid":bid, "ip":ip, "gps_lat":gps_lat, "gps_lon":gps_lon, "seat":seat, "score":score, "head":user_info['head'], "name":user_info['name']}}):
        db.res = False
        return {"code":1204, "msg":"处理超时"}
    
    game_type = room_info['game_type']
    rules = {}
    if room_info["gid"]:
        rows = db.game_rule(room_info["gid"])
    elif match_id:
        rules = {"horse":0, "grab_bar_win":"y", "grab_bar_duty":"y", "bar_win_duty":"n", "seven_pair_win":"y"}
        if game_type == 'pdk':
            rules = {"must_put":"y", "release_duty":"y", "closed_double":"y", "show_left_card":"n", "black_three_first":"n", "card_warning":1}
        rows = []
    else:    
        rows = db.room_rule(rid)
    for row in rows:
        k = row['param']
        rules[k] = row['value']
    
    game_type_name = config.GAME_TYPE_NAME.get(game_type, game_type)
    share_title = game_type_name
    share_title += u" 房间号【%s】 (分享人id:%s)" % (rid, uid)
    share_des = room_info['des']
    param_conf = db.get_param_conf(bid, 'share_url')
    share_url = "%s/?rid=%s" % (param_conf['value'], rid)
    tcp_server = db.get_connserver()
    if not tcp_server:
        tcp_server = {}
    return {"code":0, "msg":"ok", "data":{"rid":rid,"all_round":room_info['all_round'], "ranking":ranking, "room_type":room_type, "game_type_name":game_type_name, "game_type":game_type, "auto_put":auto_put, "rules":rules,"base_score":score, "room_info":room_info, "players":players, "seat":seat, "share_url":share_url, "share_title":share_title, "share_des":share_des}}

def quit_room(cp, cv, bid, uid, pwd, rid):
    rid = int(rid)
    db = dao.Game_DB()
    room_info = db.get_room(rid, bid)
    if not room_info:
        return {"code":1300, "msg":"该房间不存在"}
    if room_info['flag'] == 'n':
        return {"code":0, "msg":"退出成功"}
    #if room_info['gid']:
    #    return {"code":130001, "msg":"俱乐部房间请勿退出"}
    get_joined_room = db.get_joined_room(bid, uid)
    if not get_joined_room:
        return {"code":1301, "msg":"该帐号未进入房间无需退出"}
    status = _r.hget("r:%s" % rid, "status")
    if status:
        return {"code":1302, "msg":"游戏进行中,不能退出房间"}
    if room_info['mid']:
        return {"code":1303, "msg":"比赛进行中,不能退出房间"}
    if room_info['gid']:
        nsq_pub("game", {"b":bid, "u":uid, "t":"game","d":{"act":"dismiss_apply", "uid":uid, "rid":rid, "bid":bid}})
        return {"code":1303, "msg":"解散申请中,等待其他玩家操作"}
        #return {"code":1303, "msg":"牌局进行中,不能退出房间"}
    if room_info['admin'] == long(uid) and str(room_info['create_type']) != '1':
        i = db.admin_quit_room(rid, uid)
        joined_room = rid
    else:
        i = db.quit_room(rid, uid)
        joined_room = ""
    #if i != 1:
    #    db.res = False
    #    return {"code":1303, "msg":"房间退出失败"}
    if room_info['admin'] != long(uid):
        if not nsq_pub("status", {"b":bid, "u":str(uid), "d":{"act":"quit_room", "uid":uid, "rid":rid, "bid":bid}}):
            db.res = False
            return {"code":1304, "msg":"处理超时"}
    return {"code":0, "msg":"ok", "data":{"joined_room":joined_room}}

def dismiss_room(cp, cv, bid, uid, pwd, rid):
    rid = int(rid)
    db = dao.Game_DB()
    room_info = db.get_room(rid, bid)
    if not room_info:
        return {"code":1400, "msg":"该房间不存在"}
    if room_info['mid']:
        return {"code":1303, "msg":"比赛进行中,不能解散房间"}
    
    if not room_info['gid']:
        room = _r.hgetall("r:%s" % rid)
        if room_info['game_round'] > 0 or room.get('status') == 'start':
            nsq_pub("game", {"b":bid, "u":uid, "t":"game","d":{"act":"dismiss_apply", "uid":uid, "rid":rid, "bid":bid}})
            return {"code":1401, "msg":"游戏已准备,等待其他玩家操作"}
        
        if room_info['admin'] != long(uid):
            return quit_room(cp, cv, bid, uid, pwd, rid)
        
        i = db.dismiss_room(rid, bid, room_info['admin'])
        #if i != 1:
        #    db.res = False
        #    return {"code":1302, "msg":"房间退出失败"}
        if not nsq_pub("status", {"b":bid, "u":str(uid), "t":"game","d":{"act":"dismiss_room", "uid":uid, "rid":rid, "bid":bid}}):
            db.res = False
            return {"code":1303, "msg":"处理超时"}
    else:
        if not nsq_pub("game", {"b":bid, "u":uid, "t":"game","d":{"act":"dismiss_apply", "uid":uid, "rid":rid, "bid":bid}}):
            db.res = False
            return {"code":1303, "msg":"处理超时"}
        return {"code":200, "msg":"请等待其他玩家操作"}
    return {"code":0, "msg":"房间解散成功"}
    
def game_des(cp, cv, bid, uid):
    db = dao.Game_DB()
    conf_list = db.get_game_des()
    game_data = {}
    for game in conf_list:
        game_type = game['game_type']
        game_data[game_type] = {"name":game['name'], "des":game['des']}
    return {"code":0, "msg":"ok", "data":{'game_data':game_data}}

def feedback(bid, uid, content):
    db = dao.Game_DB()
    db.add_feedback(bid, uid, content)
    return {"code":0, "msg":"ok"}

def game_start(rid, bid):
    nsq_pub("game", {"b":"szjt", "u":"", "t":"game", "d":{"act":"game_start", "rid":rid}})
    return "ok"

def room_log(bid, uid):
    db = dao.Game_DB()
    rows = db.room_log(bid, uid)
    return {"code":0, "msg":"ok", "data":{"room_log":rows}}

def room_log_detail(bid, uid, rid):
    db = dao.Game_DB()
    rows = db.room_log_detail(rid)
    return {"code":0, "msg":"ok", "data":{"game_log_detail":rows}}

def id_auth(bid, uid, id_no, name):
    idcard_error = util.checkIdcard(id_no)
    if idcard_error:
        return {"code":2651, "msg":"身份证号码格式错误", "data":{}}
    db = dao.Game_DB()
    user_auth = db.user_auth(bid, uid)
    if user_auth:
        return {"code":2652, "msg":"你已提交实名认证信息,请勿重复提交", "data":{}}
    #db.update_user_auth(bid, uid, id_no, name)
    db.add_user_auth(bid, uid, id_no, name)
    return {"code":0, "msg":"提交成功", "data":{}} 
    
def create_match(bid, uid, game_type, score, all_player, start_time, name, des):
    if not name:
        return {"code":2700, "msg":"请输入比赛名称", "data":{}}
    if not all_player or int(all_player) < 3:
        return {"code":2701, "msg":"请输入比赛正确的比赛人数", "data":{}} 
    start_time = urllib.unquote_plus(start_time)
    db = dao.Game_DB()
    user_info = db.user_info(bid, uid)
    if user_info['mcard'] < int(all_player):
        return {"code":2701, "msg":"赛卡不足,不能创建比赛", "data":{}}
    row = db.unauth_match(bid, uid)
    if row['num'] >= 3:
        return {"code":2702, "msg":"之前创建的3个比赛未审核通过,不能再创建", "data":{}}
    if not util.check_time(start_time):
        return {"code":2703, "msg":"请输入有效的比赛开始时间", "data":{}}
    #if user_info['is_matcher'] == 1:
    #    status = 0
    #else:
    #    status = 4
    status = 0
    i, mid = db.add_match(bid, uid, game_type, score, all_player, start_time, name, des, '0')
    if i != 1:
        return {"code":2704, "msg":"创建失败", "data":{}}
    #db.join_match(bid, uid, mid, 2, 0, 1)
    #db.deduct_mcard(bid, uid, 1)
    return {"code":0, "msg":"创建成功", "data":{"mid":mid}}

def join_match(bid, uid, mid, pid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if not match:
        return {"code":2711, "msg":"比赛不存在", "data":{}}
    if match['status'] in (4, 5):
        return {"code":2712, "msg":"比赛未审核,不能加入", "data":{}}
    elif match['status'] in (1, 2):
        return {"code":2712, "msg":"比赛已经开始,不能加入", "data":{}}
    elif match['status'] == 3:
        return {"code":2712, "msg":"比赛已经结束,不能加入", "data":{}}
    
    member_info = db.match_member_info(mid, uid)
    if member_info:
        return {"code":2712, "msg":"已报名比赛，请在加入的比赛中查看", "data":{}}
    match_member_cnt = db.match_member_cnt(mid)
    join_user = match_member_cnt['number']
    if join_user >= match['all_player']:
        return {"code":2713, "msg":"比赛人员已满,不能加入", "data":{}}
    if str(match['admin']) != pid:
        match_member_info = db.match_member_info(mid, pid)
        if not match_member_info:
            return {"code":2714, "msg":"邀请人不在比赛中,请重新输入", "data":{}}
        elif match_member_info['role'] == 0:
            return {"code":2715, "msg":"邀请人不是管理员,请重新输入", "data":{}}
    #row = db.enrolled_match(bid, uid)
    #if row:
    #    return {"code":2716, "msg":"请先完成其他未完成的比赛", "data":{}}
    i = db.join_match(bid, uid, mid, 0, pid, 0)
    return {"code":0, "msg":"已提交报名比赛申请,等待审核", "data":{}}

def quit_match(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if not match:
        return {"code":2711, "msg":"比赛不存在", "data":{}}
    match_member_info = db.match_member_info(mid, uid)
    if not match_member_info:
        return {"code":2713, "msg":"邀请人不在比赛中,请重新输入", "data":{}}
    if match_member_info['verify'] == 1:
        return {"code":2714, "msg":"您已申请通过不能退出", "data":{}}
    if match['status'] in (1, 2):
        return {"code":2712, "msg":"比赛已经开始,不能退出", "data":{}}
    elif match['status'] == 3:
        return {"code":2712, "msg":"比赛已经结束,不能退出", "data":{}}
    i = db.quit_match(bid, uid, mid)
    return {"code":0, "msg":"退出成功", "data":{}}

def mine_match(bid, uid):
    db = dao.Game_DB()
    rows = db.my_match(bid, uid)
    param_conf = db.get_param_conf(bid, 'share_url')
    for match in rows:
        match['role'] = 2
        match['edit_flag'] = 'y'
        match['start_time'] = str(match['start_time'])
        game_type = match['game_type']
        match['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        mid = match['mid']
        match['share_title'] = u"快来参加比赛:%s 比赛编码【%s】(分享人id:%s)" % (match['name'], mid, uid)
        match['share_des'] = match['des']
        match['share_url'] = "%s/?mid=%s&pid=%s" % (param_conf['value'], mid, uid)
    return {"code":0, "msg":"ok", "data":{"mine_match":rows}}

def joined_match(bid, uid):
    db = dao.Game_DB()
    rows = db.joined_match(bid, uid)
    param_conf = db.get_param_conf(bid, 'share_url')
    for match in rows:
        match['edit_flag'] = 'n'
        match['start_time'] = str(match['start_time'])
        game_type = match['game_type']
        match['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        mid = match['mid']
        match['share_title'] = u"快来参加比赛:%s 比赛编码【%s】(分享人id:%s)" % (match['name'], mid, uid)
        match['share_des'] = match['des']
        match['share_url'] = "%s/?mid=%s&pid=%s" % (param_conf['value'], mid, uid)
    return {"code":0, "msg":"ok", "data":{"joined_match":rows}}

def match_info(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    param_conf = db.get_param_conf(bid, 'share_url')
    if not match:
        return {"code":2700, "msg":"ok", "data":{"match_info":match}}
    else:
        admin = match['admin']
        admin_info = db.user_info(bid, admin)
        match['point'] = admin_info['point']
        match['ctime'] = str(match['ctime'])
        match['start_time'] = str(match['start_time'])
        game_type = match['game_type']
        if game_type == 'pdk':
            player = 3
        else:
            player = 4
        match_member_cnt = db.match_member_cnt(mid)
        match['join_user'] = match_member_cnt['number']
        match['online_user'] = match_member_cnt['online_user']
        less_user = player - (match_member_cnt['number'] % player)
        if less_user == player and match_member_cnt['number'] >= player:
            match['less_user'] = 0
        else:
            match['less_user'] = less_user
            
        match['share_title'] = u"快来参加比赛:%s 比赛编码【%s】(分享人id:%s)" % (match['name'], mid, uid)
        match['share_des'] = match['des']
        match['share_url'] = "%s/?mid=%s&pid=%s" % (param_conf['value'], mid, uid)
        
        match['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        if str(match['admin']) == uid:
            role = 2
        else:
            match_member_info = db.match_member_info(mid, uid)
            if match_member_info:
                role = match_member_info['role']
            else:
                role = 0
        match['role'] = role
        ing_room = db.match_ing_room(mid, match['mround'])
        match['left_room'] = ing_room['num']
    return {"code":0, "msg":"ok", "data":{"match_info":match}} 

def match_edit(bid, uid, mid, name, des, all_player, start_time):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if not match:
        return {"code":2716, "msg":"比赛不存在", "data":{}} 
    if str(match['admin']) != uid:
        return {"code":2717, "msg":"你不是创建者不能设置管理员", "data":{}}
    if not start_time or start_time == 'None':
        start_time = str(match['start_time'])
    db.update_match_info(bid, mid, name, des, all_player, start_time)
    return {"code":0, "msg":"操作成功", "data":{}}
        
def list_match_member(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) == uid:
        admin_flag = True
        member_info = {"role":2}
    else:
        admin_flag = False
        member_info = db.match_member_info(mid, uid)
    rows = db.match_member(bid, mid, uid, admin_flag)
    for row in rows:
        if row['role'] == 1 and row['verify'] == 1 and member_info['role'] >= 1:
            child_row = db.child_member(mid, row['uid'])
            row['pass_num'] = "%s/%s" % (child_row['number'], row['num'])
        else:
            row['pass_num'] = ""
    return {"code":0, "msg":"ok", "data":{"match_member":rows}}

def del_match_member(bid, uid, mid, member):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    member_info = db.match_member_info(mid, member)
    if str(match['admin']) != uid and uid != str(member_info['pid']):
        return {"code":2721, "msg":"你不是管理员不能操作", "data":{}} 
    if match['status'] != 0:
        return {"code":2761, "msg":"比赛不在招募中,不能操作"}
    rows = db.del_match_member(mid, member)
    if str(match['admin']) == uid:
        admin_flag = True
    else:
        admin_flag = False
    rows = db.match_member(bid, mid, uid, admin_flag)
    for row in rows:
        if row['role'] == 1 and row['verify'] == 1:
            child_row = db.child_member(mid, row['uid'])
            row['pass_num'] = "%s/%s" % (child_row['number'], row['num'])
        else:
            row['pass_num'] = ""
    return {"code":0, "msg":"操作成功", "data":{"match_member":rows}}

def set_match_manager(bid, uid, mid, member, num):
    if not num:
        return {"code":2720, "msg":"请输入该赛助审核权限的数量", "data":{}}
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) != uid:
        return {"code":2721, "msg":"你不是创建者不能设置管理员", "data":{}}
    #if match['status'] == 1:
    #    return {"code":2761, "msg":"比赛正在进行,不能操作"}
    if match['status'] != 0:
        return {"code":2761, "msg":"比赛不在招募中,不能操作"}
    rows = db.set_match_manager(bid, member, mid, num)
    rows = db.match_member(bid, mid, uid, True)
    for row in rows:
        if row['role'] == 1 and row['verify'] == 1:
            child_row = db.child_member(mid, row['uid'])
            row['pass_num'] = "%s/%s" % (child_row['number'], row['num'])
        else:
            row['pass_num'] = ""
    return {"code":0, "msg":"操作成功", "data":{"match_member":rows}}

def unset_match_manager(bid, uid, mid, member):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) != uid:
        return {"code":2721, "msg":"你不是创建者不能设置赛助", "data":{}} 
    if match['status'] != 0:
        return {"code":2761, "msg":"比赛不在招募中,不能操作"}
    rows = db.unset_match_manager(bid, member, mid)
    rows = db.match_member(bid, mid, uid, True)
    for row in rows:
        if row['role'] == 1 and row['verify'] == 1:
            child_row = db.child_member(mid, row['uid'])
            row['pass_num'] = "%s/%s" % (child_row['number'], row['num'])
        else:
            row['pass_num'] = ""
    return {"code":0, "msg":"操作成功", "data":{"match_member":rows}}

def verify_match_member(bid, uid, mid, member, verify):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    member_info = db.match_member_info(mid, uid)
    if str(match['admin']) != uid:
        if member_info['role'] != 1:
            return {"code":2731, "msg":"你不是赛助不能审核", "data":{}}
        admin_flag = False
    else:
        admin_flag = True
    #if match['status'] == 1:
    #    return {"code":2761, "msg":"本轮比赛进行中,不能操作"}
    if match['status'] != 0:
        return {"code":2761, "msg":"比赛不在招募中,不能操作"}
    
    if verify == '0':
        db.del_match_member(mid, member)
    else:
        if str(match['admin']) != uid:
            row = db.child_member(mid, uid)
            if row['number'] >= member_info['num']:
                return {"code":2732, "msg":"你的审核权限数量已用完"}
        db.verify_match_member(mid, member)
    rows = db.match_member(bid, mid, uid, admin_flag)
    for row in rows:
        if row['role'] == 1 and row['verify'] == 1:
            child_row = db.child_member(mid, row['uid'])
            row['pass_num'] = "%s/%s" % (child_row['number'], row['num'])
        else:
            row['pass_num'] = ""
    return {"code":0, "msg":"操作成功", "data":{"match_member":rows}}

def start_match(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) != uid:
        return {"code":2741, "msg":"你不是创建者不能设置管理员", "data":{}}
    ing_room = db.match_ing_room(mid, 1)
    if ing_room['num'] > 0:
        return {"code":2742, "msg":"比赛正在进行不能操作", "data":{}}
    if match['status'] != 0:
        return {"code":2740, "msg":"比赛未招募中,不能开始", "data":{}}
    admin = match['admin']
    game_type = match['game_type']
    if game_type in ('pdk', 'ddz', 'ldfpf'):
        player = 3
        all_round = 3
    else:
        player = 4
        all_round = 3
    
    card = 0
    match_players = db.match_player(bid, mid)
    all_player = len(match_players)
    if all_player % player != 0 or all_player <player:
        return {"code":2743, "msg":"参数人员不满", "data":{}}
    
    match_players = list(match_players)
    random.shuffle(match_players)
    random.shuffle(match_players)
    room_num = all_player / player
    mround = 1
    #if game_type == 'pdk':
    #    base_score = 1
    #else:
    #    base_score = 100
    base_score = 100
    #rid_list = create_rid(bid, room_num)
    for i in range(room_num):
        #rid = rid_list[i]
        #n = db.add_room(rid, bid, game_type, admin, all_round, 0, player, 0, mid, mround, base_score, '', 0)
        n, rid = db.add_room(None, bid, game_type, admin, all_round, 0, player, 0, mid, mround, base_score, '', 0)
        
        for j in range(player):
            idx = i * player + j
            member = match_players[idx]
            ip = member['ip']
            p_uid = member['uid']
            if j == 0:
                room_info = {"mid":mid, "gid":"","cid":"", "status":"", "admin":admin, "dealer":p_uid, "bid":bid, "last_get_user":p_uid, "game_round":1, "all_round":all_round, "card":card, "game_type":game_type, "horse":0, "grab_bar_win":"y", "grab_bar_duty":"y", "bar_win_duty":"n", "seven_pair_win":"y"}
                logging.info(room_info)
                _r.hmset("r:%s" % rid, room_info)
                _r.hset("%s_%s" % (bid, p_uid), "rid", rid)
                _r.hset("%s_%s" % (bid, p_uid), "online", 'n')
            score = 0
            db.add_player(mid, 0, rid, p_uid, 0, 'n', ip, '', '', j+1, score)
            _r.rpush("r:%s:p" % rid, p_uid)
            #更新玩家rid
            #_r.hset("%s_%s" %(bid, p_uid), "rid", rid)
        #nsq_pub("status", {"b":bid,"u":str(uid), "t":"game", "d":{"act":"start_match", "mid":mid, "rid":rid}})
        exp_time = (datetime.datetime.now() + datetime.timedelta(seconds=60)).strftime("%Y-%m-%d %H:%M:%S")
        db.add_cron(bid, 'auto_ready', rid, 0, exp_time)
        db.commit()
        
    db.update_match_status(mid, 1)
    db.deduct_mcard(bid, uid, all_player)
    db.commit()
    nsq_pub("total", {"act":"deduct_mcard", "bid":bid, "uid":admin, "card":all_player, "mid":mid})
    return {"code":0, "msg":"操作成功", "data":{}}

def pause_match(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) != uid:
        return {"code":2751, "msg":"你不是创建者不能操作", "data":{}}
    if match['status'] != 1:
        return {"code":2752, "msg":"比赛不在进行中,不能暂停", "data":{}}
    #if match['mround'] < 3:
    #    return {"code":2753, "msg":"比赛第三轮后才可以暂停", "data":{}}
    db.update_match_status(mid, 2)
    return {"code":0, "msg":"操作成功", "data":{}}

def stop_match(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) != uid:
        return {"code":2751, "msg":"你不是创建者不能操作", "data":{}}
    db.update_match_status(mid, 3)
    nsq_pub("status", {"b":bid,"u":str(uid), "t":"game", "d":{"act":"stop_match", "mid":mid, }})
    return {"code":0, "msg":"操作成功", "data":{}}

def all_match(bid, uid):
    db = dao.Game_DB()
    enrolled_match = db.enrolled_match(bid, uid)
    if enrolled_match:
        joined_mid = enrolled_match['mid']
    else:
        joined_mid = 0
    rows = db.all_match(bid, uid)
    param_conf = db.get_param_conf(bid, 'share_url')
    for match in rows:
        if match['mid'] == joined_mid:
            match['joined_flag'] = 'y'
            match['verify'] = enrolled_match['verify']
        else:
            match['joined_flag'] = 'n'
            match['verify'] = 0
        match['role'] = 0
        match['edit_flag'] = 'n'
        game_type = match['game_type']
        match['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        mid = match['mid']
        match['share_title'] = u"快来参加比赛:%s 比赛编码【%s】(分享人id:%s)" % (match['name'], mid, uid)
        match['share_des'] = match['des']
        match['share_url'] = "%s/?mid=%s&pid=%s" % (param_conf['value'], mid, uid)
        match['start_time'] = str(match['start_time'])
    return {"code":0, "msg":"ok", "data":{"all_match":rows}}

def keep_match(bid, uid, mid):
    #暂停后重新恢复继续比赛
    #晋级和复活的人员开始新的房间
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) != uid:
        return {"code":2751, "msg":"你不是创建者不能操作", "data":{}}
    if match['status'] != 2:
        return {"code":2752, "msg":"比赛没有暂停,不能继续", "data":{}}
    mround = match['mround']
    admin = match['admin']
    game_type = match['game_type']
    ing_room = db.match_ing_room(mid, mround)
    if ing_room['num'] > 0:
        return {"code":2753, "msg":"比赛正在进行不能操作", "data":{}}
    
    if game_type in ('pdk', 'ddz', 'ldfpf'):
        player = 3
        all_round = 3
    else:
        player = 4
        all_round = 3
    card = 0
    last_player = db.last_player_score(mid)
    last_score = last_player['score']
    revive_member =  db.revive_member(mid)
    for row in revive_member:
        db.revive_member_score(mid, row['uid'], last_score)
        
    match_players = db.match_keep_palyer(mid)
    all_player = len(match_players)
    if all_player % player != 0:
        return {"code":2000, "msg":"参数人员不满", "data":{}}
    
    base_score = 100 * 3 ** (mround-1)
    if all_player == player:
        #总决赛
        all_round = 6
        #if game_type == 'pdk':
        #    all_round = 9
        #else:
        #    all_round = 5
        
    match_players = list(match_players)
    random.shuffle(match_players)
    room_num = all_player / player
    #rid_list = create_rid(bid, room_num)
    for i in range(room_num):
        #rid = rid_list[i]
        #n = db.add_room(rid, bid, game_type, admin, all_round, 0, player, 0, mid, mround, base_score, '', 0)
        n, rid = db.add_room(None, bid, game_type, admin, all_round, 0, player, 0, mid, mround, base_score, '', 0)
        
        for j in range(player):
            idx = i * player + j
            member = match_players[idx]
            ip = member['ip']
            p_uid = member['uid']
            if j == 0:
                room_info = {"mid":mid, "gid":"","cid":"", "status":"", "admin":admin, "dealer":p_uid, "bid":bid, "last_get_user":p_uid, "game_round":1, "all_round":all_round, "card":card, "game_type":game_type, "horse":0, "grab_bar_win":"y", "grab_bar_duty":"y", "bar_win_duty":"n", "seven_pair_win":"y"}
                _r.hmset("r:%s" % rid, room_info)
            
            db.add_player(mid, 0, rid, p_uid, 0, 'n', ip, '', '', j+1, member['score'])
            _r.rpush("r:%s:p" % rid, p_uid)
            _r.hset("%s_%s" % (bid, p_uid), "online", 'n')
            #_r.hset("%s_%s" %(bid, p_uid), "rid", rid)
            msg = u"恭喜你晋级下一轮,比赛继续"
            key = "%s_%s" % (bid, p_uid)
            user_data = _r.hgetall(key)
            nsq_pub("response", {"b":bid, "u":str(p_uid), "t":"game", "d":{"act":"match_keep", "msg":msg, "rid":user_data.get('rid',rid), "next_rid":rid}})
            
        #nsq_pub("status", {"b":bid,"u":str(uid), "t":"game", "d":{"act":"start_match", "mid":mid, "rid":rid}})
        exp_time = (datetime.datetime.now() + datetime.timedelta(seconds=15)).strftime("%Y-%m-%d %H:%M:%S")
        db.add_cron(bid, 'auto_ready', rid, 0, exp_time)
        db.commit()
    db.update_match_status(mid, 1)
    rows = db.match_out_palyer(mid)
    ranking = all_player + 1
    for row in rows:
        db.update_user_ranking(bid, row['uid'], mid, ranking)
        ranking += 1
    return {"code":0, "msg":"操作成功", "data":{}}

def revive_apply(bid, uid, mid, member):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if match['status'] == 1:
        return {"code":2761, "msg":"本轮比赛未结束,不能复活"}
    
    match_member_info = db.match_member_info(mid, member)
    if str(match['admin']) != uid:
        if uid == member:
            if match_member_info['res'] != 0:
                return {"code":2764, "msg":"该用户没被淘汰不能复活"}
            db.revive_apply(mid, member, None, 2)
            return {"code":2763, "msg":"请联系你的比赛邀请人进行复活"}
        else:
            return {"code":2764, "msg":"请联系你的比赛推荐人复活"}
    
    #复活用户以最后一名分数
    if match_member_info['res'] not in  (0, 2):
        return {"code":2764, "msg":"该用户没被淘汰不能复活"}
    
    user_info = db.user_info(bid, uid)
    if user_info['point'] < 1:
        return {"code":2765, "msg":"哈喽值不足,请先充值"}
    
    last_member = db.match_last_member(bid, mid)
    #if match_member_info['score'] < last_member['score']:
    #    score = last_member['score']
    #else:
    #    score = None
    score = last_member['score']
    db.revive_apply(mid, member, score)
    point = 1
    db.deduct_point(bid, uid, point)
    if str(match['admin']) != uid:
        admin_flag = False
    else:
        admin_flag = True
    nsq_pub("total", {"act":"deduct_point", "bid":bid, "uid":uid, "card":1, "mid":mid})
    rows = db.match_out_member(bid, mid, uid, admin_flag)
    return {"code":0, "msg":"操作成功", "data":{"out_member":rows}}

def revive_cancel(bid, uid, mid, member):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if match['status'] == 1:
        return {"code":2761, "msg":"本轮比赛未结束,不能复活"}
    if str(match['admin']) != uid:
        return {"code":2761, "msg":"您不是赛主,不能复活"}
    match_member_info = db.match_member_info(mid, member)
    if match_member_info['res'] !=3:
        return {"code":2764, "msg":"该用户没被复活不能取消"}
    db.revive_apply(mid, member, None, 2)
    #point = -1
    #db.deduct_point(bid, uid, point)
    admin_flag = True
    rows = db.match_out_member(bid, mid, uid, admin_flag)
    return {"code":0, "msg":"操作成功", "data":{"out_member":rows}}

def match_out_member(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if str(match['admin']) == uid:
        admin_flag = True
    else:
        admin_flag = False
    rows = db.match_out_member(bid, mid, uid, admin_flag)
    for row in rows:
        if admin_flag:
            row['vive_permission'] = 'y'
        else:
            if str(row['uid']) != uid or row['res'] == 2:
                row['vive_permission'] = 'n'
            else:
                row['vive_permission'] = 'y'
        
    return {"code":0, "msg":"ok", "data":{"out_member":rows}}

def match_result(bid, uid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    match_mround = match['mround']
    result = []
    user_info = db.user_info(bid, uid)
    if match['status'] in (1, 2, 3):
        #member_info = db.match_member_info(mid, uid)
        for mround in range(1, match_mround+1):
            #if str(match['admin']) == uid or member_info['role'] == 1:
            #    rows = db.match_score_log(mid, mround, bid)
            #    for idx, row in enumerate(rows):
            #        #row['mround'] = "%s/%s" %(mround, match_mround)
            #        row['mround'] = "%s" %mround
            #        row['ranking'] = str(idx + 1)
            #        result.append(row)
            #else:
            if 1:
                member_score = db.match_member_score(mid, mround, uid)
                if member_score:
                    score = str(member_score['score'])
                    ctime = str(member_score['ctime'])
                    member_ranking = db.match_membe_ranking(mid, mround, score, ctime)
                    ranking = str(member_ranking['num']+ 1) 
                else:
                    score = "-"
                    ranking = "-"
                data = {"mround":"%s" % mround, "score":score, "ranking":ranking, "uid":uid, "name":user_info['name']}
                result.append(data)
    del match['ctime']
    del match['start_time']

    return {"code":0, "msg":"ok", "data":{"result":result, "match_info":match}}

def match_result_detail(bid, uid, mid, mround):
    db = dao.Game_DB()
    rows = db.match_score_log(mid, mround, bid)
    for idx, row in enumerate(rows):
        row['mround'] = "%s" %(mround)
        row['ranking'] = str(idx + 1)
    return {"code":0, "msg":"ok", "data":{"result":rows}}

def all_ranking(bid, mid):
    db = dao.Game_DB()
    match = db.match_info(bid, mid)
    if match['status'] != 3:
        return {"code":2505, "msg":"请等待比赛结束后再查看", "data":{"result":[]}}
    res = []
    rows = db.all_ranking(bid, mid)
    i = 1
    for row in rows:
        row['ranking'] = i
        res.append(row)
        i += 1
    return {"code":0, "msg":"ok", "data":{"result":rows}}

def current_ranking(bid, uid):
    db = dao.Game_DB()
    ongoing_match = db.ongoing_match(bid, uid)
    if not ongoing_match:
        msg = u"恭喜你现在排名在晋级范围内"
        return {"code":0, "msg":"ok", "data":{"mround":"1" , "score":100, "ranking":"1", "msg":msg}}
    mid = ongoing_match['mid']
    mround = ongoing_match['mround']
    score = ongoing_match['user_score']
    endtime = str(ongoing_match['endtime'])
    
    member_ranking = db.current_ranking(mid, score, endtime)
    ranking = member_ranking['num']+ 1
    match_keep_palyer = db.match_keep_palyer(mid)
    mround_member = len(match_keep_palyer)
    next_num = cut_number(mround_member, 4, mround)
    if next_num > 0:
        if ranking == 1:
            msg = u"恭喜你现在排名第一"
        elif ranking <= next_num:
            msg = u"恭喜你现在排名在晋级范围内"
        else:
            row = db.middle_score(mid, next_num)
            msg = u"距离第%s名还差%s分" % (next_num, (row['score'] - score))
    else:
        if ranking == 1:
            msg = u"恭喜你现在排名第一"
        else:
            row = db.first_score(mid)
            msg = u"距离第%s名还差%s分" % (1, (row['score'] - score))
    return {"code":0, "msg":"ok", "data":{"mround":"%s" % mround, "score":score, "ranking":str(ranking), "msg":msg}}


def cut_number(n=100, m=4, mround=1):
    if mround == 1:
        #if n % (m*2) == 0:
        #    return n/2
        #elif n == m:
        if n == m:
            return 0
    else:
        n /= 2
    if n < m:
        return 0
    elif n == m:
        return m
    j = 0
    for i in range(20):
        if n <= m*2**i:
            j = i
            break
    if mround == 1:
        return m*2**(j-1)
    p = n - m*2**(j-1)
    q = m*2**j - n
    if p > q:
        return m*2**j
    return m*2**(j-1)

def match_game_over(reader, bid, uid, data):
    mid = data.get("match_id")
    game_round = int(data['game_round'])
    db = dao.Game_DB()
    if mid:
        match = db.match_info(bid, mid)
        game_type = match['game_type']
        match_status = match['status']
        mround = match['mround']
        #不同轮数底分不同
        all_round = int(data['all_round'])
        #match_score = mround * match['score'] + all_round - game_round
        #mround_room = db.mround_room(mid, mround)
        #if mround_room['num'] == 1:
        #    match_score = 1200 + game_round - 1
        endtime = time.strftime("%Y-%m-%d %H:%M:%S")
        
        for ps in data['player_card']:
            member = ps['uid']
            #score = int(ps['score']) * match_score
            score = int(ps['score'])
            db.update_score(mid, member, score, endtime)
            db.add_match_log(mid, mround, data['rid'], game_round, member, score)
            logging.info(u"比赛:%s第%s轮房间;%s结束第%s小局,玩家:%s,分数:%s" % (mid, mround, data['rid'], game_round, member, score))
                    
def match_room_over(reader, bid, uid, data):
    mid = data.get("match_id")
    gid = data.get("gid")
    db = dao.Game_DB()
    if gid:
        if not db.get_ing_game(gid):
            db.update_game_status(gid, 2)
            logging.info(u"俱乐部牌局结束:%s" % gid)
        else:
            logging.info(u"俱乐部牌局%s,房间%s结束,等待其他房间" % (gid, data.get("rid", "")))
        return
    if mid:
        logging.info(u"比赛中房间完成结束游戏:%s" % mid)
        match = db.match_info(bid, mid)
        game_type = match['game_type']
        match_status = match['status']
        mround = match['mround']
        ing_room = db.match_ing_room(mid, mround)
        ing_room_num = ing_room['num']
        for ps in data['player_stat']:
            member = ps['uid']
            member_info = db.match_member_info(mid, member)
            db.add_match_score(mid, mround, member, member_info['score'])
            logging.info(u"比赛:%s第%s轮,房间:%s结束,玩家:%s当前分数:%s" % (mid, mround, data['rid'], member, member_info['score']))
        
        #next_ing_room = db.match_ing_room(mid, mround+1)
        #next_room_num = next_ing_room['num']
        pre_round_players = db.pre_round_players(mid, mround)
        #推送通知
        for p in pre_round_players:
            p_uid = p['uid']
            msg = u"本轮比赛结束,请耐心等待其他玩家完成比赛以决定你的排名,祝您好运~"
            key = "%s_%s" % (bid, p_uid)
            user_data = _r.hgetall(key)
            message = {"b":bid, "u":str(p_uid), "t":"game", "d":{"act":"match_room_over", "mid":mid,"left_room":ing_room_num, "msg":msg, "rid":str(user_data.get("rid", 0))}}
            nsq_pub("response", message)
        
        if ing_room_num == 0:
            #当轮比赛结束,没有进行的房间
            #取出这一轮玩家人员,计算出来该晋级的人数,更新被淘汰的人员状态为0,晋级人员为1
            logging.info(u"比赛:%s第%s轮结束" % (mid, mround))
            #pre_round_players = db.match_keep_palyer(mid)
            
            if game_type == 'pdk':
                player = 3
                all_round = 3
            else:
                player = 4
                all_round = 3
            
            #更新用户排名
            rk = 0
            for pre_player in pre_round_players:
                rk += 1
                db.update_user_ranking(bid, pre_player['uid'], mid, rk)
                
            next_round_num = cut_number(len(pre_round_players), player, mround)
            if next_round_num:
                next_round_players = pre_round_players[:next_round_num]
                for p in next_round_players:
                    db.match_palyer_in(mid, p['uid'])
                out_players = pre_round_players[next_round_num:]
                j = 0
                for p in out_players:
                    j += 1
                    db.match_palyer_out(mid, p['uid'])
                    msg = u"很遗憾,您被淘汰"
                    ranking = j + next_round_num
                    #db.update_user_ranking(bid, p['uid'], mid, ranking)
                    key = "%s_%s" % (bid, p['uid'])
                    user_data = _r.hgetall(key)
                    message = {"b":bid, "u":str(p['uid']), "t":"game", "d":{"act":"match_out", "mid":mid, "msg":msg, "ranking":ranking, "rid":str(user_data.get('rid', 0))}}
                    nsq_pub("response", message)
            
                #更新比赛为开始下一轮
                mround += 1
                db.update_match_round(mid, mround)
                
                #判断比赛状态是否继续,分配房间,如果是总决赛all_round为9
                if match_status == 3:
                    #推送消息暂停比赛
                    #rk = 0
                    for pre_player in pre_round_players:
                        msg = u"比赛结束~"
                        #rk += 1
                        #db.update_user_ranking(bid, pre_player['uid'], mid, rk)
                        key = "%s_%s" % (bid, pre_player['uid'])
                        user_data = _r.hgetall(key)
                        message = {"b":bid, "u":str(pre_player['uid']), "t":"game", "d":{"act":"match_over", "mid":mid, "msg":msg, "rid":str(user_data.get('rid', 0))}}
                        nsq_pub("response", message)
                elif match_status == 2:
                    #推送消息暂停比赛
                    for pre_player in next_round_players:
                        msg = u"恭喜你晋级下一轮,比赛暂停中,休息一下稍后再开始下一轮"
                        key = "%s_%s" % (bid, pre_player['uid'])
                        user_data = _r.hgetall(key)
                        message = {"b":bid, "u":str(pre_player['uid']), "t":"game", "d":{"act":"match_pause", "mid":mid, "msg":msg, "rid":str(user_data.get('rid', 0))}}
                        nsq_pub("response", message)
                elif match_status == 1:
                    #分配房间
                    admin = match['admin']
                    card = 0
                    match_players = list(next_round_players)
                    all_player = len(match_players)
                    random.shuffle(match_players)
                    random.shuffle(match_players)
                    room_num = all_player / player
                    
                    base_score = 100 * 3 ** (mround-1)
                    #if game_type == 'pdk':
                    #    base_score = 1
                    #最后一轮总决赛
                    if all_player == player:
                        all_round = 6
                    
                    #rid_list = create_rid(bid, room_num)
                    for i in range(room_num):
                        (n, rid) = db.add_room(None, bid, game_type, admin, all_round, 0, player, 0, mid, mround, base_score, '', 0)
                        #rid = rid_list[i]
                        #n = db.add_room(rid, bid, game_type, admin, all_round, 0, player, 0, mid, mround, base_score, '', 0)
                        
                        for j in range(player):
                            idx = i * player + j
                            member = match_players[idx]
                            ip = member.get('ip','')
                            p_uid = member['uid']
                            if j == 0:
                                room_info = {"mid":mid, "gid":"","cid":"", "status":"", "admin":admin, "dealer":p_uid, "bid":bid, "last_get_user":p_uid, "game_round":1, "all_round":all_round, "card":card, "game_type":game_type, "horse":0, "grab_bar_win":"y", "grab_bar_duty":"y", "bar_win_duty":"n", "seven_pair_win":"y"}
                                _r.hmset("r:%s" % rid, room_info)
                            
                            db.add_player(mid, 0, rid, p_uid, 0, 'n', ip, '', '', j+1, member['score'])
                            _r.rpush("r:%s:p" % rid, p_uid)
                            key = "%s_%s" % (bid, p_uid)
                            user_data = _r.hgetall(key)
                            msg = u"恭喜你晋级,可以进入下一轮"
                            message = {"b":bid, "u":str(p_uid), "t":"game", "d":{"act":"match_in", "mid":mid, "msg":msg, "rid":str(user_data.get('rid', 0)), "next_rid":rid}}
                            nsq_pub("response", message)
                            
                            #_r.hset(key, "rid", rid)
                            _r.hset(key, "online", 'n')
                            
                            logging.info(u"用户晋级:%s,%s,%s" % (mid, rid, p_uid))
                        nsq_pub("status", {"b":bid,"u":str(uid), "t":"game", "d":{"act":"start_match", "mid":mid, "rid":rid, "next_rid":rid}})
                        exp_time = (datetime.datetime.now() + datetime.timedelta(seconds=15)).strftime("%Y-%m-%d %H:%M:%S")
                        db.add_cron(bid, 'auto_ready', rid, 0, exp_time)
                        db.commit()
            else:
                db.match_over(mid)
                rk = 0
                for pre_player in pre_round_players:
                    rk += 1
                    msg = u"比赛结束~ 排名:%s" % rk
                    key = "%s_%s" % (bid, pre_player['uid'])
                    user_data = _r.hgetall(key)
                    message = {"b":bid, "u":str(pre_player['uid']), "t":"game", "d":{"act":"match_over", "mid":mid, "msg":msg, "rid":str(user_data.get('rid', 0))}}
                    nsq_pub("response", message)
                logging.info(u"比赛结束:%s" % mid)
        

def clear_redis():
    db = dao.Game_DB()
    rows = db.query("select * from t_room where flag='n'")
    for row in rows:
        rid = row['rid']
        allkeys = _r.keys("*%s*" % rid)
        for key in allkeys:
            print key
            _r.delete(key)

def created_room(cp, cv, bid, uid, pwd):
    db = dao.Game_DB()
    rows = db.created_room(uid, 'y')
    for row in rows:
        rid = row['rid']
        game_type = row['game_type']
        game_type_name = config.GAME_TYPE_NAME.get(game_type, game_type)
        row['game_type_name'] = game_type_name
        row['ctime'] = str(row['ctime'])
        room_players = db.query_room_players(rid, bid)
        row['room_players'] = room_players
        row['share_title'] = u"%s 房间号【%s】 (分享人id:%s)" % (game_type_name, rid, uid)
        row['share_des'] = row['des'] 
        param_conf = db.get_param_conf(bid, 'share_url')
        row['share_url'] = "%s/?rid=%s" % (param_conf['value'], rid)
    return {"code":0, "data":{"room_list":rows, "create_type":"1"}}

def created_log(cp, cv, bid, uid, pwd):
    db = dao.Game_DB()
    rows = db.created_room(uid, 'n')
    for row in rows:
        rid = row['rid']
        game_type = row['game_type']
        row['game_type_name'] = config.GAME_TYPE_NAME.get(game_type, game_type)
        row['ctime'] = str(row['ctime'])
        room_players = db.query_room_players(rid, bid)
        row['room_players'] = room_players
    return {"code":0, "data":{"room_list":rows}}

if __name__ == '__main__':
    #print get_phone_model('Dalvik/2.1.0 (Linux; U; Android 5.1; vivo X6D Build/LMY47I)')
    for i in range(1,100):
        print 4*i, cut_number(4*i,4,1)

